package com.xtaller.easy.admin.base;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.xtaller.common.bean.CacheInfo;
import com.xtaller.common.bean.JWTResult;
import com.xtaller.common.bean.Where;
import com.xtaller.common.convert.J;
import com.xtaller.common.convert.L;
import com.xtaller.common.convert.V;
import com.xtaller.common.kit.JwtKit;
import com.xtaller.easy.admin.config.R;
import com.xtaller.easy.admin.service.impl.BaseUserLabelService;
import com.xtaller.easy.admin.service.impl.BaseUserService;
import com.xtaller.easy.admin.service.impl.SysMenuService;
import com.xtaller.easy.admin.tps.CacheKit;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author Taller
 * @create 2018-04-13 17:46
 */
public class TApi {
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    public CacheKit cacheKit;
    @Autowired
    public SysMenuService menuService;
    @Autowired
    public BaseUserService userService;
    /**
     * 获取header的token
     * */
    public String getToken(){
        return request.getHeader("token");
    }
    /**
     * 通过jwt token认证信息获取userId
     * */
    public String getUserIdByToken(){
        JWTResult jwt = JwtKit.validateJWT(getToken());
        if (jwt.isSuccess()) {
            Claims claims = jwt.getClaims();
            return claims.getId();
        }else {
            return "0";
        }
    }
    public CacheInfo getCacheInfoByToken(){
        return cacheKit.getCacheInfo(getUserIdByToken());
    }
    /**
     * 读取个人信息
     * */
    public JSONObject getUserInfo(String userId, String module){
        JSONObject object = new JSONObject();
        // 校验子系统权限
        JSONObject w = new JSONObject();
        w.put("code", module);
        w.put("userId", userId);
        List<JSONObject> roles = userService.getRoleByCode(w);
        // 检查属性
        object.put("check", -1);        // 尚未配置权限数据
        // 基本信息
        List<JSONObject> labels = userService.getUserLabel(userId, userService.getLabelByUserIds(userId+""));
        object.put("label", formatLabel(labels));
        // 权限信息
        object.put("auth", new ArrayList<>());
        if(roles.size() == 0)
            return object;
        object.put("check", 1);

        w = new JSONObject();
        w.put("code", module);
        w.put("roleIds", L.getAttrs(roles, "roleId"));
        // 权限菜单信息
        JSONObject auth = userService.getAuthByRoleIds(w);
        List<JSONObject> menus = J.o2l(auth.get("menus"));
        object.put("auth", L.list2Tree(menus, "0"));

        // 权限按钮
        List<JSONObject> btns = new ArrayList<>();
        if(menus.size() > 0){
            for(JSONObject menu:menus){
                JSONObject btn = new JSONObject();
                if(menu.getString("url").trim().length() > 0) {
                    btn.put("url", menu.getString("url"));
                    btn.put("btns", J.o2l(menu.get("btns")));
                    btns.add(btn);
                }
            }
        }
        object.put("btns", btns);
        return  object;
    }
    private List<JSONObject> getModuleByCode(String code){
        List<JSONObject> module = menuService.getMenu();
        if(module.size() > 0){
            for(JSONObject item:module){
                if(V.isEqual(item.getString("code"), code)){
                    module = J.o2l(item.get("menus"));
                }
            }
        }
        return module;
    }
    private JSONObject formatLabel(List<JSONObject> labels){
        JSONObject label = new JSONObject();
        if(labels.size() > 0){
            for(JSONObject item:labels){
                label.put(item.getString("code"), formatLabelAttr(J.o2l(item.get("children"))));
            }
        }
        return label;
    }
    private JSONObject formatLabelAttr(List<JSONObject> childrens){
        JSONObject label = new JSONObject();
        if(childrens.size() > 0){
            for(JSONObject children:childrens){
                label.put(children.getString("code"), children.get("txt"));
            }
        }
        return label;
    }
    /**
     * 转化成easyui datagrid的数据格式
     * */
    public Object data2Grid(int total, Object object){
        JSONObject grid = new JSONObject();
        grid.put("total", total);
        grid.put("rows", J.formatObject(object));
        return grid;
    }
    public Object data2Grid(Object object){
        JSONObject grid = J.o2j(object);
        grid.put("total", grid.get("total"));
        grid.put("rows", J.formatObject(J.o2l(grid.get("records"))));
        grid.remove("records");
        return grid;
    }
    /**
     * 格式化对象删除多余属性
     * creator\createTime\reviser\reviseTime\isDel
     * */
    public JSONObject formatObject(Object object){
        JSONObject o = J.o2j(object);
        o.remove("creator");
        o.remove("createTime");
        o.remove("reviser");
        o.remove("reviseTime");
        o.remove("isDel");
        return o;
    }
    public List<JSONObject> formatList(Object objects){
        List<JSONObject> jsons = J.o2l(objects);
        for(JSONObject object:jsons){
            object.remove("creator");
            object.remove("createTime");
            object.remove("reviser");
            object.remove("reviseTime");
            object.remove("isDel");
        }
        return jsons;
    }
    /**
     * 格式化对象删除多余属性
     * reviser\reviseTime\isDel
     * */
    public JSONObject fm2(Object object){
        JSONObject o = J.o2j(object);
        o.remove("reviser");
        o.remove("reviseTime");
        o.remove("isDel");
        return o;
    }
    public List<JSONObject> fl2(Object objects){
        List<JSONObject> jsons = J.o2l(objects);
        for(JSONObject object:jsons){
            object.remove("reviser");
            object.remove("reviseTime");
            object.remove("isDel");
        }
        return jsons;
    }

    // 转成lablel
    public String o2q(String query){
        JSONObject object = J.s2j(query);
        String where = "";
        Map<String, Object> map = J.o2m(object);
        Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();
        int index = 1;
        while (entries.hasNext()) {
            Map.Entry<String, Object> entry = entries.next();
            String tem = "";
            if(index == 1) {
                tem = " ";
            }else {
                tem = " or ";
            }
            if(entry.getValue().toString().trim().length() > 0){
                index += 1;
                where += (tem + "(code='"+entry.getKey()+"' and val like '%"+entry.getValue()+"%') ");
            }
        }
        return String.format(" and (%s)", where);
    }

}
